<template>
	<div class="resourcesFile">
		<el-card shadow="hover">
			<div class="resources-ictures mb15">
				<el-form :inline="true" :model="formData" label-width="120px" class="demo-form-inline">
					<el-row>
						<el-col :span="7">
							<el-form-item label="关键词:" style="width: 100%">
								<el-input maxlength="200" v-model="formData.keyWord" placeholder="关键词" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="7">
							<el-form-item label="上传时间" style="width: 100%">
								<el-date-picker style="width: 100%" value-format="YYYY-MM-DD" v-model="formData.time" type="date" placeholder="选择日期">
								</el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="7">
							<div style="padding-left: 10px">
								<el-button type="primary" @click="searchFun">搜索</el-button>
								<el-button @click="resetFrom">重置</el-button>
							</div>
						</el-col>
						<el-col :span="3">
							<div style="padding-left: 10px; text-align: right">
								<el-button type="success" @click="setDialogVisible(true)">新增</el-button>
							</div>
						</el-col>
					</el-row>
				</el-form>
				<el-table v-loading="loading" :data="tableData" style="width: 100%">
					<el-table-column prop="orderNumber" width="80px" label="序号"> </el-table-column>
					<el-table-column prop="name" label="名称"> </el-table-column>
					<el-table-column label="上传时间">
						<template #default="scope">
							{{ returnDateText(scope.row.uploadDate) }}
						</template>
					</el-table-column>
					<el-table-column width="400px" label="下载链接">
						<template #default="scope">
							<el-link :href="scope.row.imgUrl" target="_blank">{{ scope.row.imgUrl }}</el-link>
							<!-- <a :href="scope.row.imgUrl" target="_blank" class="uri-box">
								{{ scope.row.imgUrl }}
							</a> -->
						</template>
					</el-table-column>
					<el-table-column label="编辑" width="180px" align="center">
						<template #default="scope">
							<el-button text :loading="deleteLoading" type="primary" @click="showPdfFun(scope.row)">查看</el-button>
							<el-button text :loading="deleteLoading" type="primary" @click="renameFun(scope.row)">重命名</el-button>
							<el-button text :loading="deleteLoading" type="danger" @click="beforeDelete(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination
					@size-change="onHandleSizeChange"
					@current-change="onHandleCurrentChange"
					class="mt15"
					:pager-count="5"
					:page-sizes="[10, 20, 30]"
					v-model:current-page="page.pageNum"
					background
					v-model:page-size="page.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="page.total"
				>
				</el-pagination>
			</div>
		</el-card>
		<el-dialog v-model="dialogVisible" title="上传图片" width="50%" :destroy-on-close="true">
			<AttachmentUpload />
			<template #footer>
				<span class="dialog-footer">
					<el-button :loading="dialogLoading" type="primary" @click="uploadImgs">关闭并重载列表</el-button>
				</span>
			</template>
		</el-dialog>
		<AttachmentSelectorDialog
			v-model="attachmentSelectorDialogVisible"
			@submit="
				(list) => {
					console.log('选中的列表', list);
				}
			"
			:max-length="1"
		/>
		<!-- 侧边的附件预览 -->
		<el-drawer v-model="attachmentVisible" title="附件预览" direction="rtl" size="50%">
			<div class="drawer-box">
				<iframe class="drawer-iframe" :src="attachmentUrl" frameborder="0"></iframe>
			</div>
		</el-drawer>
		<!-- 侧边的pdf预览 -->
		<el-drawer v-model="pdfVisible" title="pdf预览" direction="rtl" size="50%">
			<div class="drawer-box">
				<Pdfh5 v-if="pdfVisible" :pdfUrl="pdfUrl" />
			</div>
		</el-drawer>
	</div>
</template>
<script setup name="ResourcesFile">
import 'dayjs/locale/zh-cn';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useResourceApi } from '/@/api/resource';
import AttachmentUpload from '/@/components/attachmentSelector/AttachmentUpload.vue';
import AttachmentSelectorDialog from '/@/components/attachmentSelector/AttachmentSelectorDialog.vue';
import { timeFormat } from '/@/utils/filters';
import { deepCopy } from '/@/utils';
import { checkFormatByFileName } from '/@/utils/commonRequest';
import Pdfh5 from '/@/components/common/pdfh5/Pdfh5.vue';

const { delAttachmentById, getAttachmentList, reNameAttachment } = useResourceApi();

let loading = ref(false);
let dialogVisible = ref(false);
let dialogLoading = ref(false);
let deleteLoading = ref(false);
let attachmentSelectorDialogVisible = ref(false);
let attachmentVisible = ref(false);
let pdfVisible = ref(false);
let pdfUrl = ref('');
let attachmentUrl = ref('');

let formData = ref({
	keyWord: '',
	time: null,
});

let tableData = ref([]);

let srcList = ref([]);

let page = ref({
	pageSize: 10,
	current: 1,
	total: 0,
});

init();

function init() {
	getList();
}

function searchFun() {
	if (loading.value) {
		return;
	}
	page.value = {
		pageSize: page.value.pageSize,
		current: 1,
		total: page.value.total,
	};
	getList();
}

async function getList() {
	if (loading.value) {
		return;
	}
	loading.value = true;

	try {
		let params = {
			current: page.value.current,
			pageSize: page.value.pageSize,
			picName: formData.value.keyWord,
			status: 1, // 如果是null，表示查所有，是否展示 0->禁用；1->启用
			createTime: formData.value.time,
			// type:"jpg" // 图片类型
		};
		let res = await getAttachmentList(params);
		if (res.code !== 200) {
			loading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		loading.value = false;
		page.value = {
			pageSize: res.data.pageSize,
			current: res.data.current,
			total: res.data.total,
		};

		let tempList = res.data.data.map((item, index) => {
			return {
				isChecked: false,
				id: item.id,
				orderNumber: (res.data.current - 1) * 10 + index + 1,
				name: item.picName,
				uploadDate: item.createTime,
				imgUrl: item.picUrl,
				fullName: item.picUrl,
			};
		});

		tableData.value = tempList;

		setSrcList(tempList);
	} catch (error) {
		loading.value = false;
		ElMessage({
			type: 'error',
			message: '获取附件列表失败',
		});
	}
}

// 分页改变
const onHandleSizeChange = (val) => {
	page.value.pageSize = val;
	getList();
};
// 分页改变
const onHandleCurrentChange = (val) => {
	page.value.current = val;
	getList();
};

function setSrcList(list) {
	srcList.value = list.map((item) => {
		return item.imgUrl ? item.imgUrl : '';
	});
}

async function deleteFun(id, state = 0) {
	// console.log(id);
	if (deleteLoading.value) {
		return;
	}
	deleteLoading.value = true;
	let params = {
		idList: [id],
		status: state, // 是否展示 0->禁用；1->启用
	};
	try {
		let res = await delAttachmentById(params);
		if (res.code !== 200) {
			deleteLoading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		ElMessage({
			type: 'success',
			message: '删除成功！',
		});
		deleteLoading.value = false;
		getList();
	} catch (error) {
		deleteLoading.value = false;
	}
}

// 编辑
async function editFun(item) {
	if (loading.value) {
		return;
	}

	loading.value = true;

	try {
		let params = {
			id: item.id,
			picName: item.name,
		};
		let res = await reNameAttachment(params);
		if (res.code !== 200) {
			loading.value = false;
			ElMessage({
				type: 'error',
				message: res.data.msg,
			});
			return;
		}
		loading.value = false;
		ElMessage({
			type: 'success',
			message: '重命名成功！',
		});
		getList();
	} catch (error) {
		loading.value = false;
		ElMessage({
			type: 'error',
			message: '重命名失败',
		});
	}
}

function resetFrom() {
	formData.value = {
		keyWord: '',
		time: null,
	};
	// page.value = {
	//     pageSize: page.value.pageSize,
	//     current: 1,
	//     total: page.value.total,
	// };
	// getList();
}

function beforeDelete(row) {
	ElMessageBox.confirm(`确认删除附件：${row.name}?`, '删除附件', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			deleteFun(row.id);
		})
		.catch(() => {});
}

function renameFun(item) {
	ElMessageBox.prompt('请输入新名称', '重命名', {
		inputValue: item.name + '',
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
		inputErrorMessage: '名称不能为空',
	})
		.then(({ value }) => {
			let tempItem = deepCopy(item);
			tempItem.name = value;
			editFun(tempItem);
		})
		.catch(() => {});
}

// 调用组件打开文件
function showPdfFun(item) {
	pdfUrl.value = '';
	attachmentUrl.value = '';
	let fileFullName = item.fullName; // 拿到文件的全称，带后缀
	let openUrl = '';
	// 相关技术文档
	// https://www.jianshu.com/p/db5eb1872f32
	if (checkFormatByFileName(fileFullName) === 'pdf') {
		// PDF预览
		openUrl = item.imgUrl;
		pdfUrl.value = openUrl;
		pdfVisible.value = true;
		return;
	}
	if (checkFormatByFileName(fileFullName) === 'office') {
		// office预览
		// openUrl = "https://view.officeapps.live.com/op/view.aspx?src=" + encodeURIComponent(item.imgUrl + "");
		openUrl = 'http://view.xdocin.com/xdoc?_xdoc=' + item.imgUrl;
	}
	if (checkFormatByFileName(fileFullName) === 'image') {
		// 图片预览
		openUrl = item.imgUrl;
		ElMessageBox.alert(`<img src="${openUrl}" style="object-fit: cover;">`, 'HTML String', {
			dangerouslyUseHTMLString: true,
			title: '图片预览',
			showConfirmButton: false,
		});
		return;
	}
	if (checkFormatByFileName(fileFullName) === 'video') {
		// 视频预览
		openUrl = item.imgUrl;
		ElMessageBox.alert(
			`<video width='100%' height='240' controls><source src='${openUrl}'  type='video/mp4'>您的浏览器不支持 HTML5 video 标签。</video>`,
			'HTML String',
			{
				dangerouslyUseHTMLString: true,
				title: '视频预览',
				showConfirmButton: false,
			}
		);
		return;
	}
	if (openUrl === '') {
		return;
	}
	attachmentUrl.value = openUrl;
	attachmentVisible.value = true;
}

// 是否显示查看按钮
function isShowView(item) {
	let fileFullName = item.fullName;
	let state = checkFormatByFileName(fileFullName) !== 'other';
	return state;
}

function setDialogVisible(state) {
	dialogVisible.value = state;
}

// function setAttachmentSelectorDialogVisible(state) {
// 	attachmentSelectorDialogVisible.value = state;
// }

function uploadImgs() {
	dialogVisible.value = false;
	getList();
}

function returnDateText(params) {
	let returnText = '';
	if (!params) {
		returnText = '';
	} else {
		let paramsDate = timeFormat(params);
		returnText = `${paramsDate}`;
	}
	return returnText;
}
</script>
<style lang="scss" scoped>
.resourcesFile {
	.el-row {
		margin-bottom: 20px;
	}
	.uri-box {
		word-wrap: break-word;
		word-break: break-all;
		white-space: normal;
		color: blue;
	}
	.line-box {
		display: flex;
		align-items: center;
		.input-name {
			width: 100px;
			text-align: right;
			padding-right: 10px;
		}
		.input-box {
			display: flex;
			flex: 1;
			overflow: hidden;
			align-items: center;
			.input-box-p {
				padding: 0 15px;
			}
			&.input-box-btns {
				width: 100%;
			}
		}
	}
}
.drawer-box {
	display: flex;
	flex: 1;
	height: 100%;
	overflow: overlay;
	.drawer-iframe {
		display: flex;
		flex: 1;
	}
}
</style>
